package com.example.todolist.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.todolist.dto.sys.TemplateData;
import com.example.todolist.dto.sys.WxMssVo;
import com.example.todolist.response.BaseResponse;
import com.example.todolist.response.SystemResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author :xiaosheng
 * @description :
 * @create :2022-03-21 15:40:00
 */
@Service
@Slf4j
@AllArgsConstructor
public class UserSubscribeServiceImpl {
    @Autowired
    private RestTemplate restTemplate;

    public String Auth(String openId,String date,String titlie) {
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getWxSession();
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id("Q0ptzgVtY5hnt2BoYZrHw7IROu8rBjO62SeSJ23R7-Q");//订阅消息模板id
        wxMssVo.setPage("pages/my_plan/my_plan");

        Map<String, TemplateData> m = new HashMap<>(2);
        m.put("date1", new TemplateData(date));
        m.put("thing11", new TemplateData("【"+titlie+"】计划记得按时开始完成计划喔"));
        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        System.out.println(responseEntity);
        return responseEntity.getBody();
    }


    public String getWxSession() {
        String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx36809f0f5ffc6c49&secret=e74f504d932f269a46f5742c8bb2988c";
        String response = restTemplate.getForObject(urlString,String.class);
        JSONObject jsonObject = JSONObject.parseObject(response);
        log.info("微信用户:{}",jsonObject);
        if (null == jsonObject) {
            throw new RuntimeException("调用微信接口失败");
        }
        return (String) jsonObject.get("access_token");
    }
}
